package com.cysion.study.ui

import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.CLog
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.adapter.CommentsChatAdapter
import com.cysion.study.entity.CommentsEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.HideUtil
import com.cysion.study.widget.ShowToast
import com.scwang.smartrefresh.layout.constant.RefreshState
import kotlinx.android.synthetic.main.activity_comments_detail.*

//留言详情
class CommentsDetailActivity : BaseActivity(), View.OnClickListener {


    override fun getLayoutId(): Int = R.layout.activity_comments_detail
    var fromUserId: String = ""
    private lateinit var proAdapter: CommentsChatAdapter
    private val noticeList: MutableList<CommentsEntity> = mutableListOf()
    private var curPage = 1

    override fun initView() {
        fromUserId = intent.getBundleExtra("key").getString("fromUserId")

        HideUtil.init(this)
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("留言详情")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        initRefreshLayout()
        initRecyclerView()


        iv_emj.setOnClickListener(this)
        tv_send.setOnClickListener(this)
        iv_img.setOnClickListener(this)
//        commentEntity = intent.getBundleExtra("key").getSerializable("obj") as CommentsEntity?
        getDataList(curPage)


    }

    //    初始化刷新控件
    private fun initRefreshLayout() {
        smartLayout.setOnRefreshListener {
            curPage = 1
            getDataList(curPage)
            smartLayout.setEnableLoadMore(true)

        }
        smartLayout.setOnLoadMoreListener {
            getDataList(curPage)
        }
    }

    //初始化列表
    private fun initRecyclerView() {
        rv_view.isNestedScrollingEnabled = false
        proAdapter = CommentsChatAdapter(noticeList, Box.context)
        rv_view.adapter = proAdapter
        rv_view.layoutManager = LinearLayoutManager(Box.context)

        rv_view.setOnTouchListener { v, event ->
            iv_img.visibility = View.GONE
            HideUtil.init(this, rv_view)
            false
        }
        /*rv_view.setOnClickListener {
            iv_img.visibility=View.GONE
        }*/

        et_content.setOnXFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                iv_img.visibility = View.GONE
            }
        }

    }


    private fun getDataList(page: Int) {
        Alert.loading(self)
        ApiClient.api.getChatList(UserCache.token, "").compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    /*if (curPage == 1) {
                        noticeList.clear()
                        if (noticeList.size == 0) {
                            multiView.showEmpty()
                        }
                    }
                    if (it.size <= 0) {
                    } else {
                        curPage++
                        noticeList.addAll(it)
                        proAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }*/
                    if (it.size == 0) {
                        multiView.showEmpty()
                    } else {
                        noticeList.clear()
                        noticeList.addAll(it)
                        proAdapter.notifyDataSetChanged()
                        multiView.showContent()
                    }

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_emj -> {//表情
                iv_img.visibility = View.VISIBLE
                hideKeybord()
                et_content.clearFocus()
            }
            R.id.tv_send -> {//发送
                iv_img.visibility = View.GONE
                var content = et_content.textEx.toString().trim()
                //type 内容形式 0.文字内容 1.图片内容
                sendContent(content, "0")
                et_content.setTextEx("")
                hideKeybord()
                et_content.clearFocus()
            }
            R.id.iv_img -> {//图片选择

            }
        }
    }


    private fun sendContent(content: String, type: String) {
        Alert.loading(self)
        ApiClient.api.saveOrUpdate(UserCache.token, fromUserId, type, "", content)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
//                    getDataList(0)
                    var chat: CommentsEntity = CommentsEntity("", "", "", ""
                        , "", "", "", "", ""
                        , "", "", "", "", "")
                    chat.userName = UserCache.userInfo?.nickName.toString()
                    chat?.userHeadImageUrl = UserCache.userInfo?.headImageUrl.toString()
                    chat?.content = content
                    //fromUserType0.教师(自己) 1.家长(发送信息人)
                    chat?.fromUserType = "0"
                    chat?.let { it1 -> noticeList.add(it1) }
                    CLog.i("###=" + noticeList.size)
                    proAdapter.notifyDataSetChanged()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private fun stopRefresh() {
        if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }
    }

    fun hideKeybord() {
        val imm = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(this.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }

    override fun closeMvp() {
    }

}
